/**
 * 缓存工具
 */
// 获取缓存
export function getCacheSync<T>(key: string): T | undefined {
  return uni.getStorageSync(key) as T | undefined
}

// 设置缓存
export function setCache<T>(key: string, data: T): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.setStorage({
      key,
      data,
      success: () => resolve(),
      fail: (e) => reject(e),
    })
  })
}

// 移除缓存
export function removeCache(key: string): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.removeStorage({
      key,
      success: () => resolve(),
      fail: (e) => reject(e),
    })
  })
}

// 批量移除缓存
export function removeCaches(keys: string[]): Promise<void[]> {
  return Promise.all(keys.map((key) => removeCache(key)))
}

// 移除特定缓存
export function removeSpecificCaches(keyMatcher: (key: string) => boolean): Promise<void[]> {
  return new Promise((resolve, reject) => {
    uni.getStorageInfo({
      success: ({ keys }) => {
        const removeTasks = keys.reduce<Promise<void>[]>((tasks, key) => {
          // 匹配Key
          const matched = keyMatcher(key)
          if (matched) {
            const task = removeCache(key)
            tasks.push(task)
          }
          return tasks
        }, [])
        resolve(Promise.all(removeTasks))
      },
      fail: (e) => reject(e),
    })
  })
}
